package com.kh.rationaldrugreview.controller;

import com.kh.rationaldrugreview.service.DrugKnowledgeGraphService;
import com.kh.rationaldrugreview.service.PDFTextExtractor;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 药品知识图谱构建接口
 * 提供PDF上传、实体提取、关系识别等功能
 */
@Slf4j
@RestController
@RequestMapping("/api/knowledge-graph")
@RequiredArgsConstructor
@Tag(name = "Knowledge Graph", description = "药品知识图谱构建接口")
public class KnowledgeGraphController {
    
    private final DrugKnowledgeGraphService knowledgeGraphService;
    private final PDFTextExtractor pdfTextExtractor;
    
    /**
     * 上传PDF药品说明书并构建知识图谱
     * 
     * @param file PDF文件（药品说明书）
     * @return 提取的实体和关系信息
     */
    @PostMapping(value = "/upload-and-extract", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传PDF并提取知识图谱", 
              description = "上传药品说明书PDF文件，自动提取实体和关系，构建知识图谱并保存到Neo4j")
    public ResponseEntity<?> uploadPDFAndExtract(
            @Parameter(description = "药品说明书PDF文件", required = true)
            @RequestParam("file") MultipartFile file) {
        
        log.info("Received PDF file: {}, size: {} bytes", 
            file.getOriginalFilename(), file.getSize());
        
        // 验证文件
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(
                createErrorResponse("文件不能为空"));
        }
        
        String filename = file.getOriginalFilename();
        if (filename == null || !filename.toLowerCase().endsWith(".pdf")) {
            return ResponseEntity.badRequest().body(
                createErrorResponse("只支持PDF文件格式"));
        }
        
        // 文件大小限制（10MB）
        if (file.getSize() > 10 * 1024 * 1024) {
            return ResponseEntity.badRequest().body(
                createErrorResponse("文件大小不能超过10MB"));
        }
        
        try {
            // 处理PDF并构建知识图谱
            DrugKnowledgeGraphService.KnowledgeGraphResult result = 
                knowledgeGraphService.processPDFToKnowledgeGraph(file);
            
            if ("SUCCESS".equals(result.getStatus())) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "知识图谱构建成功");
                response.put("filename", filename);
                response.put("entitiesCount", result.getEntities().size());
                response.put("relationshipsCount", result.getRelationships().size());
                response.put("entities", result.getEntities());
                response.put("relationships", result.getRelationships());
                response.put("metadata", result.getMetadata());
                
                // 实体类型统计
                Map<String, Long> entityTypeCount = new HashMap<>();
                result.getEntities().forEach(entity -> 
                    entityTypeCount.merge(entity.getType(), 1L, Long::sum));
                response.put("entityTypeCount", entityTypeCount);
                
                // 关系类型统计
                Map<String, Long> relationshipTypeCount = new HashMap<>();
                result.getRelationships().forEach(rel -> 
                    relationshipTypeCount.merge(rel.getType(), 1L, Long::sum));
                response.put("relationshipTypeCount", relationshipTypeCount);
                
                log.info("Knowledge graph built successfully for file: {}", filename);
                return ResponseEntity.ok(response);
                
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse(result.getMessage()));
            }
            
        } catch (IOException e) {
            log.error("IO error processing PDF", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(createErrorResponse("文件处理失败: " + e.getMessage()));
        } catch (Exception e) {
            log.error("Error building knowledge graph", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(createErrorResponse("知识图谱构建失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取PDF文件信息（不进行知识提取）
     */
    @PostMapping(value = "/pdf-info", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "获取PDF信息", description = "获取PDF文件的基本信息，不进行实体提取")
    public ResponseEntity<?> getPDFInfo(@RequestParam("file") MultipartFile file) {
        
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(
                createErrorResponse("文件不能为空"));
        }
        
        try {
            // 保存临时文件
            String tempPath = System.getProperty("java.io.tmpdir") + "/" + 
                System.currentTimeMillis() + "_" + file.getOriginalFilename();
            
            file.transferTo(new java.io.File(tempPath));
            
            // 获取PDF信息
            PDFTextExtractor.PDFInfo info = pdfTextExtractor.getPDFInfo(tempPath);
            
            // 提取前几页文本作为预览
            String previewText = pdfTextExtractor.extractTextFromPages(tempPath, 1, 2);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("filename", file.getOriginalFilename());
            response.put("fileSize", file.getSize());
            response.put("pageCount", info.getPageCount());
            response.put("title", info.getTitle());
            response.put("author", info.getAuthor());
            response.put("previewText", previewText.substring(0, Math.min(1000, previewText.length())));
            
            // 删除临时文件
            new java.io.File(tempPath).delete();
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Error getting PDF info", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(createErrorResponse("获取PDF信息失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取知识图谱统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取知识图谱统计", description = "获取当前知识图谱中的实体和关系统计信息")
    public ResponseEntity<?> getGraphStatistics() {
        try {
            Map<String, Object> stats = knowledgeGraphService.getGraphStatistics();
            stats.put("success", true);
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("Error getting graph statistics", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(createErrorResponse("获取统计信息失败: " + e.getMessage()));
        }
    }
    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    @Operation(summary = "健康检查", description = "检查知识图谱服务是否正常")
    public ResponseEntity<?> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "DrugKnowledgeGraph");
        health.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(health);
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> error = new HashMap<>();
        error.put("success", false);
        error.put("error", message);
        error.put("timestamp", System.currentTimeMillis());
        return error;
    }
}